package com.epay.epay.service;

import com.epay.epay.config.PayConfig;
import com.epay.epay.model.PayResult;
import com.epay.epay.util.MD5Signer;
import com.epay.epay.util.SnowflakeIdGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.TreeMap;


@Service
public class PayServiceImpl implements IPayService{

    @Autowired
    SnowflakeIdGenerator snowflakeIdGenerator;

    @Autowired
    PayConfig payConfig;

    @Autowired
    RestTemplate restTemplate;

    ObjectMapper objectMapper = new ObjectMapper();

    private boolean isPc(HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        if(userAgent.contains("Android") || userAgent.contains("iPhone")||userAgent.contains("iPad")){
            return false;
        }
        return true;
    }

    @Override
    public PayResult pay(BigDecimal amount, HttpServletRequest request) {
        TreeMap<String,String> map = new TreeMap<>();
        map.put("pid",payConfig.getMerchantId());
        map.put("type","wxpay");
//        map.put("device",isPc(request)?"pc":"wechat");
        map.put("device","jump");
        map.put("money", amount.toString());
        map.put("name","测试商品");
        map.put("notify_url",payConfig.getNotifyUrl());
        map.put("return_url",payConfig.getReturnUrl());
        map.put("clientip","192.168.1.100");
        map.put("out_trade_no", snowflakeIdGenerator.nextId()+"");
        map.put("sign_type","MD5");
        map.put("sign", MD5Signer.generateMD5Sign(map,payConfig.getMerchantSecret()));

        System.out.println(map);
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        map.forEach((k,v)->{
            formData.add(k,v);
        });

        System.out.println(formData);

        HttpHeaders headers = new HttpHeaders();
//        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formData,headers);
        ResponseEntity<String> response = null;
        PayResult payResult = new PayResult();
        try {
            response = restTemplate.postForEntity(payConfig.getPayUrl(), entity, String.class);
            System.out.println(response.getBody());
            if(response.getStatusCode().is2xxSuccessful()){
                payResult= objectMapper.readValue(response.getBody(),PayResult.class);
            }
        } catch (RestClientException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();

        } catch (JsonProcessingException e) {
            e.printStackTrace();

        }

        return payResult;
    }
}
